
local ffi = require("ffi")
function find(rom,...)
    local len = select('#',...);
    local t = {...};
    local size = ffi.sizeof(rom);
    for i=0,size-1 do
        if(t[1]==rom[i])then
            local match = true;
            for j=0,len-1 do
                if(t[1+j] and t[1+j]~=rom[i+j])then
                    match = false;
                    break;
                end
            end
            if(match)then
                print(string.format('%X',i));
            end
        end
    end
end

function find2(rom)
    local size = ffi.sizeof(rom);
    local c = 0;
    local address = 0;
    local r = ffi.cast('uint32_t*',rom+2)
    for i=0,size/4-1 do
        if(r[i]>0 and r[i]<0x1024*1024)then
            c = c + 1;
        else
            if(c>0x80)then
                print(string.format('%X',address-0x100000));
            end
            c = 0;
            address = i * 4;
        end
    end
end

assert(#arg>0,"no file");
local file = io.open(arg[1],"rb");
local data = file:read('*a');
local rom = ffi.new('uint8_t[?]',#data);
ffi.copy(rom,data);

-- 从rom dump出来的不用置换
-- 查找第4代rom，直接查找文件，需要交换高低位
-- for i=0,ffi.sizeof(rom)-1,2 do
--     local t = rom[i+0];
--     rom[i+0] = rom[i+1];
--     rom[i+1] = t;
-- end

--查找按键程序1
find(rom,0x10,0x2d,nil,nil,0x12,0x2d,nil,nil);

print('----------------');

--查找跳转表
--find(rom,0x10,0x10,0xc0,0x00,nil,nil,0x65,0x00,nil,nil)

find2(rom,
0x4E,0xFB,nil,nil,
0x60,0x00,nil,nil,
0x60,0x00,nil,nil,
0x60,0x00,nil,nil
);

--查找mslug1
-- find(rom,
-- 0,0x3c,0x0,0x1,
-- 0x4e,0x75
-- );




